{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0, 0, 0, 0, 'no'], [0, 0, 0, 1, 'no'], [0, 1, 0, 1, 'yes'], [0, 1, 1, 0, 'yes'], [0, 0, 0, 0, 'no'], [1, 0, 0, 0, 'no'], [1, 0, 0, 1, 'no'], [1, 1, 1, 1, 'yes'], [1, 0, 1, 2, 'yes'], [1, 0, 1, 2, 'yes'], [2, 0, 1, 2, 'yes'], [2, 0, 1, 1, 'yes'], [2, 1, 0, 1, 'yes'], [2, 1, 0, 2, 'yes'], [2, 0, 0, 0, 'no']]\n",
      "0.9709505944546686\n"
     ]
    }
   ],
   "source": [
    "# -*- coding: UTF-8 -*-\n",
    "from math import log\n",
    "\n",
    "\"\"\"\n",
    "函数说明:创建测试数据集\n",
    "\n",
    "Parameters:\n",
    "    无\n",
    "Returns:\n",
    "    dataSet - 数据集\n",
    "    labels - 分类属性\n",
    "Author:\n",
    "    Jack Cui\n",
    "Modify:\n",
    "    2017-07-20\n",
    "\"\"\"\n",
    "def createDataSet():\n",
    "    dataSet = [[0, 0, 0, 0, 'no'],  #数据集\n",
    "            [0, 0, 0, 1, 'no'],\n",
    "            [0, 1, 0, 1, 'yes'],\n",
    "            [0, 1, 1, 0, 'yes'],\n",
    "            [0, 0, 0, 0, 'no'],\n",
    "            [1, 0, 0, 0, 'no'],\n",
    "            [1, 0, 0, 1, 'no'],\n",
    "            [1, 1, 1, 1, 'yes'],\n",
    "            [1, 0, 1, 2, 'yes'],\n",
    "            [1, 0, 1, 2, 'yes'],\n",
    "            [2, 0, 1, 2, 'yes'],\n",
    "            [2, 0, 1, 1, 'yes'],\n",
    "            [2, 1, 0, 1, 'yes'],\n",
    "            [2, 1, 0, 2, 'yes'],\n",
    "            [2, 0, 0, 0, 'no']]\n",
    "    labels = ['年龄', '有工作', '有自己的房子', '信贷情况']#分类属性\n",
    "    return dataSet, labels  #返回数据集和分类属性\n",
    "\n",
    "\"\"\"\n",
    "函数说明:计算给定数据集的经验熵(香农熵)\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 数据集\n",
    "Returns:\n",
    "    shannonEnt - 经验熵(香农熵)\n",
    "Author:\n",
    "    Jack Cui\n",
    "Modify:\n",
    "    2017-03-29\n",
    "\"\"\"\n",
    "def calcShannonEnt(dataSet):\n",
    "    numEntires = len(dataSet)#返回数据集的行数\n",
    "    labelCounts = {}#保存每个标签(Label)出现次数的字典\n",
    "    for featVec in dataSet:#对每组特征向量进行统计\n",
    "        currentLabel = featVec[-1]#提取标签(Label)信息\n",
    "        if currentLabel not in labelCounts.keys():#如果标签(Label)没有放入统计次数的字典,添加进去\n",
    "            labelCounts[currentLabel] = 0\n",
    "        labelCounts[currentLabel] += 1 #Label计数\n",
    "    shannonEnt = 0.0 #经验熵(香农熵)\n",
    "    for key in labelCounts: #计算香农熵\n",
    "        prob = float(labelCounts[key]) / numEntires#选择该标签(Label)的概率\n",
    "        shannonEnt -= prob * log(prob, 2)#利用公式计算\n",
    "    return shannonEnt #返回经验熵(香农熵)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    dataSet, features = createDataSet()\n",
    "    print(dataSet)\n",
    "    print(calcShannonEnt(dataSet))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第0个特征的增益为0.083\n",
      "第1个特征的增益为0.324\n",
      "第2个特征的增益为0.420\n",
      "第3个特征的增益为0.363\n",
      "最优特征索引值:2\n"
     ]
    }
   ],
   "source": [
    "# -*- coding: UTF-8 -*-\n",
    "from math import log\n",
    "\n",
    "\"\"\"\n",
    "函数说明:计算给定数据集的经验熵(香农熵)\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 数据集\n",
    "Returns:\n",
    "    shannonEnt - 经验熵(香农熵)\n",
    "Author:\n",
    "    Jack Cui\n",
    "Modify:\n",
    "    2017-03-29\n",
    "\"\"\"\n",
    "def calcShannonEnt(dataSet):\n",
    "    numEntires = len(dataSet)#返回数据集的行数\n",
    "    labelCounts = {} #保存每个标签(Label)出现次数的字典\n",
    "    for featVec in dataSet:#对每组特征向量进行统计\n",
    "        currentLabel = featVec[-1]#提取标签(Label)信息\n",
    "        if currentLabel not in labelCounts.keys():#如果标签(Label)没有放入统计次数的字典,添加进去\n",
    "            labelCounts[currentLabel] = 0\n",
    "        labelCounts[currentLabel] += 1 #Label计数\n",
    "    shannonEnt = 0.0#经验熵(香农熵)\n",
    "    for key in labelCounts: #计算香农熵\n",
    "        prob = float(labelCounts[key]) / numEntires#选择该标签(Label)的概率\n",
    "        shannonEnt -= prob * log(prob, 2)#利用公式计算\n",
    "    return shannonEnt#返回经验熵(香农熵)\n",
    "\n",
    "\"\"\"\n",
    "函数说明:创建测试数据集\n",
    "\n",
    "Parameters:\n",
    "    无\n",
    "Returns:\n",
    "    dataSet - 数据集\n",
    "    labels - 分类属性\n",
    "Author:\n",
    "    Jack Cui\n",
    "Modify:\n",
    "    2017-07-20\n",
    "\"\"\"\n",
    "def createDataSet():\n",
    "    dataSet = [[0, 0, 0, 0, 'no'],#数据集\n",
    "            [0, 0, 0, 1, 'no'],\n",
    "            [0, 1, 0, 1, 'yes'],\n",
    "            [0, 1, 1, 0, 'yes'],\n",
    "            [0, 0, 0, 0, 'no'],\n",
    "            [1, 0, 0, 0, 'no'],\n",
    "            [1, 0, 0, 1, 'no'],\n",
    "            [1, 1, 1, 1, 'yes'],\n",
    "            [1, 0, 1, 2, 'yes'],\n",
    "            [1, 0, 1, 2, 'yes'],\n",
    "            [2, 0, 1, 2, 'yes'],\n",
    "            [2, 0, 1, 1, 'yes'],\n",
    "            [2, 1, 0, 1, 'yes'],\n",
    "            [2, 1, 0, 2, 'yes'],\n",
    "            [2, 0, 0, 0, 'no']]\n",
    "    labels = ['年龄', '有工作', '有自己的房子', '信贷情况']#分类属性\n",
    "    return dataSet, labels#返回数据集和分类属性\n",
    "\n",
    "\"\"\"\n",
    "函数说明:按照给定特征划分数据集\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 待划分的数据集\n",
    "    axis - 划分数据集的特征\n",
    "    value - 需要返回的特征的值\n",
    "Returns:\n",
    "    无\n",
    "Author:\n",
    "    Jack Cui\n",
    "Modify:\n",
    "    2017-03-30\n",
    "\"\"\"\n",
    "def splitDataSet(dataSet, axis, value):       \n",
    "    retDataSet = [] #创建返回的数据集列表\n",
    "    for featVec in dataSet:#遍历数据集\n",
    "        if featVec[axis] == value:\n",
    "            reducedFeatVec = featVec[:axis] #去掉axis特征\n",
    "            reducedFeatVec.extend(featVec[axis+1:]) #将符合条件的添加到返回的数据集\n",
    "            retDataSet.append(reducedFeatVec)\n",
    "    return retDataSet   #返回划分后的数据集\n",
    "\n",
    "\"\"\"\n",
    "函数说明:选择最优特征\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 数据集\n",
    "Returns:\n",
    "    bestFeature - 信息增益最大的(最优)特征的索引值\n",
    "Author:\n",
    "    Jack Cui\n",
    "Modify:\n",
    "    2017-03-30\n",
    "\"\"\"\n",
    "def chooseBestFeatureToSplit(dataSet):\n",
    "    numFeatures = len(dataSet[0]) - 1 #特征数量\n",
    "    baseEntropy = calcShannonEnt(dataSet)#计算数据集的香农熵\n",
    "    bestInfoGain = 0.0 #信息增益\n",
    "    bestFeature = -1  #最优特征的索引值\n",
    "    for i in range(numFeatures):#遍历所有特征\n",
    "        #获取dataSet的第i个所有特征\n",
    "        featList = [example[i] for example in dataSet]\n",
    "        uniqueVals = set(featList) #创建set集合{},元素不可重复\n",
    "        newEntropy = 0.0 #经验条件熵\n",
    "        for value in uniqueVals: #计算信息增益\n",
    "            subDataSet = splitDataSet(dataSet, i, value)#subDataSet划分后的子集\n",
    "            prob = len(subDataSet) / float(len(dataSet)) #计算子集的概率\n",
    "            newEntropy += prob * calcShannonEnt(subDataSet)#根据公式计算经验条件熵\n",
    "        infoGain = baseEntropy - newEntropy#信息增益\n",
    "        print(\"第%d个特征的增益为%.3f\" % (i, infoGain))#打印每个特征的信息增益\n",
    "        if (infoGain > bestInfoGain):#计算信息增益\n",
    "            bestInfoGain = infoGain#更新信息增益，找到最大的信息增益\n",
    "            bestFeature = i#记录信息增益最大的特征的索引值\n",
    "    return bestFeature#返回信息增益最大的特征的索引值\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    dataSet, features = createDataSet()\n",
    "    print(\"最优特征索引值:\" + str(chooseBestFeatureToSplit(dataSet)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'有自己的房子': {0: {'有工作': {0: 'no', 1: 'yes'}}, 1: 'yes'}}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# -*- coding: UTF-8 -*-\n",
    "from matplotlib.font_manager import FontProperties\n",
    "import matplotlib.pyplot as plt\n",
    "from math import log\n",
    "import operator\n",
    "\n",
    "\"\"\"\n",
    "函数说明:计算给定数据集的经验熵(香农熵)\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 数据集\n",
    "Returns:\n",
    "    shannonEnt - 经验熵(香农熵)\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def calcShannonEnt(dataSet):\n",
    "    numEntires = len(dataSet) #返回数据集的行数\n",
    "    labelCounts = {}#保存每个标签(Label)出现次数的字典\n",
    "    for featVec in dataSet: #对每组特征向量进行统计\n",
    "        currentLabel = featVec[-1]#提取标签(Label)信息\n",
    "        if currentLabel not in labelCounts.keys():#如果标签(Label)没有放入统计次数的字典,添加进去\n",
    "            labelCounts[currentLabel] = 0\n",
    "        labelCounts[currentLabel] += 1#Label计数\n",
    "    shannonEnt = 0.0#经验熵(香农熵)\n",
    "    for key in labelCounts:#计算香农熵\n",
    "        prob = float(labelCounts[key]) / numEntires#选择该标签(Label)的概率\n",
    "        shannonEnt -= prob * log(prob, 2)#利用公式计算\n",
    "    return shannonEnt #返回经验熵(香农熵)\n",
    "\n",
    "\"\"\"\n",
    "函数说明:创建测试数据集\n",
    "\n",
    "Parameters:\n",
    "    无\n",
    "Returns:\n",
    "    dataSet - 数据集\n",
    "    labels - 特征标签\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-20\n",
    "\"\"\"\n",
    "def createDataSet():\n",
    "    dataSet = [[0, 0, 0, 0, 'no'], #数据集\n",
    "            [0, 0, 0, 1, 'no'],\n",
    "            [0, 1, 0, 1, 'yes'],\n",
    "            [0, 1, 1, 0, 'yes'],\n",
    "            [0, 0, 0, 0, 'no'],\n",
    "            [1, 0, 0, 0, 'no'],\n",
    "            [1, 0, 0, 1, 'no'],\n",
    "            [1, 1, 1, 1, 'yes'],\n",
    "            [1, 0, 1, 2, 'yes'],\n",
    "            [1, 0, 1, 2, 'yes'],\n",
    "            [2, 0, 1, 2, 'yes'],\n",
    "            [2, 0, 1, 1, 'yes'],\n",
    "            [2, 1, 0, 1, 'yes'],\n",
    "            [2, 1, 0, 2, 'yes'],\n",
    "            [2, 0, 0, 0, 'no']]\n",
    "    labels = ['年龄', '有工作', '有自己的房子', '信贷情况']#特征标签\n",
    "    return dataSet, labels #返回数据集和分类属性\n",
    "\n",
    "\"\"\"\n",
    "函数说明:按照给定特征划分数据集\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 待划分的数据集\n",
    "    axis - 划分数据集的特征\n",
    "    value - 需要返回的特征的值\n",
    "Returns:\n",
    "    无\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def splitDataSet(dataSet, axis, value):       \n",
    "    retDataSet = []#创建返回的数据集列表\n",
    "    for featVec in dataSet:#遍历数据集\n",
    "        if featVec[axis] == value:\n",
    "            reducedFeatVec = featVec[:axis]#去掉axis特征\n",
    "            reducedFeatVec.extend(featVec[axis+1:])#将符合条件的添加到返回的数据集\n",
    "            retDataSet.append(reducedFeatVec)\n",
    "    return retDataSet#返回划分后的数据集\n",
    "\n",
    "\"\"\"\n",
    "函数说明:选择最优特征\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 数据集\n",
    "Returns:\n",
    "    bestFeature - 信息增益最大的(最优)特征的索引值\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-20\n",
    "\"\"\"\n",
    "def chooseBestFeatureToSplit(dataSet):\n",
    "    numFeatures = len(dataSet[0]) - 1#特征数量\n",
    "    baseEntropy = calcShannonEnt(dataSet) #计算数据集的香农熵\n",
    "    bestInfoGain = 0.0 #信息增益\n",
    "    bestFeature = -1 #最优特征的索引值\n",
    "    for i in range(numFeatures):#遍历所有特征\n",
    "        #获取dataSet的第i个所有特征\n",
    "        featList = [example[i] for example in dataSet]\n",
    "        uniqueVals = set(featList)#创建set集合{},元素不可重复\n",
    "        newEntropy = 0.0 #经验条件熵\n",
    "        for value in uniqueVals:#计算信息增益\n",
    "            subDataSet = splitDataSet(dataSet, i, value)#subDataSet划分后的子集\n",
    "            prob = len(subDataSet) / float(len(dataSet))#计算子集的概率\n",
    "            newEntropy += prob * calcShannonEnt(subDataSet) #根据公式计算经验条件熵\n",
    "        infoGain = baseEntropy - newEntropy #信息增益\n",
    "        # print(\"第%d个特征的增益为%.3f\" % (i, infoGain)) #打印每个特征的信息增益\n",
    "        if (infoGain > bestInfoGain):#计算信息增益\n",
    "            bestInfoGain = infoGain#更新信息增益，找到最大的信息增益\n",
    "            bestFeature = i#记录信息增益最大的特征的索引值\n",
    "    return bestFeature#返回信息增益最大的特征的索引值\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "函数说明:统计classList中出现此处最多的元素(类标签)\n",
    "\n",
    "Parameters:\n",
    "    classList - 类标签列表\n",
    "Returns:\n",
    "    sortedClassCount[0][0] - 出现此处最多的元素(类标签)\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def majorityCnt(classList):\n",
    "    classCount = {}\n",
    "    for vote in classList:#统计classList中每个元素出现的次数\n",
    "        if vote not in classCount.keys():classCount[vote] = 0   \n",
    "        classCount[vote] += 1\n",
    "        #根据字典的值降序排序\n",
    "    sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True) \n",
    "    return sortedClassCount[0][0]#返回classList中出现次数最多的元素\n",
    "\n",
    "\"\"\"\n",
    "函数说明:创建决策树\n",
    "\n",
    "Parameters:\n",
    "    dataSet - 训练数据集\n",
    "    labels - 分类属性标签\n",
    "    featLabels - 存储选择的最优特征标签\n",
    "Returns:\n",
    "    myTree - 决策树\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-25\n",
    "\"\"\"\n",
    "def createTree(dataSet, labels, featLabels):\n",
    "    classList = [example[-1] for example in dataSet]#取分类标签(是否放贷:yes or no)\n",
    "    if classList.count(classList[0]) == len(classList):#如果类别完全相同则停止继续划分\n",
    "        return classList[0]\n",
    "    if len(dataSet[0]) == 1:#遍历完所有特征时返回出现次数最多的类标签\n",
    "        return majorityCnt(classList)\n",
    "    bestFeat = chooseBestFeatureToSplit(dataSet) #选择最优特征\n",
    "    bestFeatLabel = labels[bestFeat] #最优特征的标签\n",
    "    featLabels.append(bestFeatLabel)\n",
    "    myTree = {bestFeatLabel:{}}#根据最优特征的标签生成树\n",
    "    del(labels[bestFeat]) #删除已经使用特征标签\n",
    "    featValues = [example[bestFeat] for example in dataSet] #得到训练集中所有最优特征的属性值\n",
    "    uniqueVals = set(featValues)#去掉重复的属性值\n",
    "    for value in uniqueVals: #遍历特征，创建决策树。                       \n",
    "        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), labels, featLabels)\n",
    "    return myTree\n",
    "\n",
    "\"\"\"\n",
    "函数说明:获取决策树叶子结点的数目\n",
    "\n",
    "Parameters:\n",
    "    myTree - 决策树\n",
    "Returns:\n",
    "    numLeafs - 决策树的叶子结点的数目\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def getNumLeafs(myTree):\n",
    "    numLeafs = 0 #初始化叶子\n",
    "    #python3中myTree.keys()返回的是dict_keys,\n",
    "    #不在是list,所以不能使用myTree.keys()[0]的方法获取结点属性，可以使用list(myTree.keys())[0]\n",
    "    firstStr = next(iter(myTree))\n",
    "    secondDict = myTree[firstStr]#获取下一组字典\n",
    "    for key in secondDict.keys():\n",
    "        if type(secondDict[key]).__name__=='dict': #测试该结点是否为字典，如果不是字典，代表此结点为叶子结点\n",
    "            numLeafs += getNumLeafs(secondDict[key])\n",
    "        else:   numLeafs +=1\n",
    "    return numLeafs\n",
    "\n",
    "\"\"\"\n",
    "函数说明:获取决策树的层数\n",
    "\n",
    "Parameters:\n",
    "    myTree - 决策树\n",
    "Returns:\n",
    "    maxDepth - 决策树的层数\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def getTreeDepth(myTree):\n",
    "    maxDepth = 0 #初始化决策树深度\n",
    "    #python3中myTree.keys()返回的是dict_keys,不在是list,所以不能使用myTree.keys()[0]的方法获取结点属性，\n",
    "    #可以使用list(myTree.keys())[0]\n",
    "    firstStr = next(iter(myTree))\n",
    "    secondDict = myTree[firstStr]#获取下一个字典\n",
    "    for key in secondDict.keys():\n",
    "        if type(secondDict[key]).__name__=='dict': #测试该结点是否为字典，如果不是字典，代表此结点为叶子结点\n",
    "            thisDepth = 1 + getTreeDepth(secondDict[key])\n",
    "        else:   thisDepth = 1\n",
    "        if thisDepth > maxDepth: maxDepth = thisDepth #更新层数\n",
    "    return maxDepth\n",
    "\n",
    "\"\"\"\n",
    "函数说明:绘制结点\n",
    "\n",
    "Parameters:\n",
    "    nodeTxt - 结点名\n",
    "    centerPt - 文本位置\n",
    "    parentPt - 标注的箭头位置\n",
    "    nodeType - 结点格式\n",
    "Returns:\n",
    "    无\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def plotNode(nodeTxt, centerPt, parentPt, nodeType):\n",
    "    arrow_args = dict(arrowstyle=\"<-\") #定义箭头格式\n",
    "    font = FontProperties(fname=r\"c:\\windows\\fonts\\simsun.ttc\", size=14) #设置中文字体\n",
    "    createPlot.ax1.annotate(nodeTxt, xy=parentPt,  xycoords='axes fraction',#绘制结点\n",
    "        xytext=centerPt, textcoords='axes fraction',\n",
    "        va=\"center\", ha=\"center\", bbox=nodeType, arrowprops=arrow_args, FontProperties=font)\n",
    "\n",
    "\"\"\"\n",
    "函数说明:标注有向边属性值\n",
    "\n",
    "Parameters:\n",
    "    cntrPt、parentPt - 用于计算标注位置\n",
    "    txtString - 标注的内容\n",
    "Returns:\n",
    "    无\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def plotMidText(cntrPt, parentPt, txtString):\n",
    "    xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0] #计算标注位置                   \n",
    "    yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]\n",
    "    createPlot.ax1.text(xMid, yMid, txtString, va=\"center\", ha=\"center\", rotation=30)\n",
    "\n",
    "\"\"\"\n",
    "函数说明:绘制决策树\n",
    "\n",
    "Parameters:\n",
    "    myTree - 决策树(字典)\n",
    "    parentPt - 标注的内容\n",
    "    nodeTxt - 结点名\n",
    "Returns:\n",
    "    无\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def plotTree(myTree, parentPt, nodeTxt):\n",
    "    decisionNode = dict(boxstyle=\"sawtooth\", fc=\"0.8\")  #设置结点格式\n",
    "    leafNode = dict(boxstyle=\"round4\", fc=\"0.8\") #设置叶结点格式\n",
    "    numLeafs = getNumLeafs(myTree)#获取决策树叶结点数目，决定了树的宽度\n",
    "    depth = getTreeDepth(myTree) #获取决策树层数\n",
    "    firstStr = next(iter(myTree)) #下个字典                                                 \n",
    "    cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)#中心位置\n",
    "    plotMidText(cntrPt, parentPt, nodeTxt) #标注有向边属性值\n",
    "    plotNode(firstStr, cntrPt, parentPt, decisionNode) #绘制结点\n",
    "    secondDict = myTree[firstStr] #下一个字典，也就是继续绘制子结点\n",
    "    plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD#y偏移\n",
    "    for key in secondDict.keys():                               \n",
    "        if type(secondDict[key]).__name__=='dict':#测试该结点是否为字典，如果不是字典，代表此结点为叶子结点\n",
    "            plotTree(secondDict[key],cntrPt,str(key)) #不是叶结点，递归调用继续绘制\n",
    "        else:  #如果是叶结点，绘制叶结点，并标注有向边属性值                                             \n",
    "            plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW\n",
    "            plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)\n",
    "            plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))\n",
    "    plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD\n",
    "\n",
    "\"\"\"\n",
    "函数说明:创建绘制面板\n",
    "\n",
    "Parameters:\n",
    "    inTree - 决策树(字典)\n",
    "Returns:\n",
    "    无\n",
    "Author:\n",
    "    Jack Cui\n",
    "Blog:\n",
    "    http://blog.csdn.net/c406495762\n",
    "Modify:\n",
    "    2017-07-24\n",
    "\"\"\"\n",
    "def createPlot(inTree):\n",
    "    fig = plt.figure(1, facecolor='white')#创建fig\n",
    "    fig.clf()#清空fig\n",
    "    axprops = dict(xticks=[], yticks=[])\n",
    "    createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) #去掉x、y轴\n",
    "    plotTree.totalW = float(getNumLeafs(inTree))  #获取决策树叶结点数目\n",
    "    plotTree.totalD = float(getTreeDepth(inTree)) #获取决策树层数\n",
    "    plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;#x偏移\n",
    "    plotTree(inTree, (0.5,1.0), '') #绘制决策树\n",
    "    plt.show()  #显示绘制结果     \n",
    "\n",
    "if __name__ == '__main__':\n",
    "    dataSet, labels = createDataSet()\n",
    "    featLabels = []\n",
    "    myTree = createTree(dataSet, labels, featLabels)\n",
    "    print(myTree)  \n",
    "    createPlot(myTree)  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
